package com.netdevsdk.demo.user;

import javax.swing.JOptionPane;

import com.netdevsdk.demo.NetDemo;
import com.netdevsdk.demo.util.Common;
import com.netdevsdk.lib.NetDEVSDKLib.NETDEV_USER_DETAIL_INFO_S;
import com.netdevsdk.lib.NetDEVSDKLib.NETDEV_USER_LEVEL_E;

/**
 * @description To add user.
 * @introduction Only support NVR.
 */
public class AddUser {
    /**
     * @description To add user.
     * @introduction Calling the interface of NETDEV_CreateUser.
     */
	@SuppressWarnings("deprecation")
    public static void addUser() {
		if(null == NetDemo.lpUserID)
		{
			JOptionPane.showMessageDialog(null, "Please Login device first. error code"+NetDemo.netdevsdk.NETDEV_GetLastError());
			return;
		}
		NetDemo.jButtonUserListGetUserList.doClick();
		NETDEV_USER_DETAIL_INFO_S stUserInfo = new NETDEV_USER_DETAIL_INFO_S();
		if(NetDemo.jTextFieldAddUserUserName.getText()==null||NetDemo.jTextFieldAddUserUserName.getText().equals("")) 
		{
			JOptionPane.showMessageDialog(null, "Username can not be null");
			return;
		}
		if(NetDemo.UserListTableModel.getRowCount()>0) 
		{
			for(int i=0;i<NetDemo.UserListTableModel.getRowCount();i++) {
				String username=(String) NetDemo.UserListTableModel.getValueAt(i, 1);
				if(NetDemo.jTextFieldAddUserUserName.getText().equals(username)) {
					JOptionPane.showMessageDialog(null, "User is alerady existence");
					NetDemo.jTextFieldAddUserUserName.setText(null);
					NetDemo.jTextFieldlAddUserPasswd.setText(null);
					return;
				}
			}
		}
		if(NetDemo.jTextFieldlAddUserPasswd.getText()==null||NetDemo.jTextFieldlAddUserPasswd.getText().equals("")) 
		{
			JOptionPane.showMessageDialog(null, "Password can not null");
			return;
		}
		Common.stringToByteArray(NetDemo.jTextFieldAddUserUserName.getText(), stUserInfo.szUserName);
		Common.stringToByteArray(NetDemo.jTextFieldlAddUserPasswd.getText(), stUserInfo.szPassword);
		if(NetDemo.jComboBoxAddUserUserType.getSelectedIndex() == 0)
		{
			stUserInfo.udwLevel = NETDEV_USER_LEVEL_E.NETDEV_USER_LEVEL_OPERATOR;
		}
		else if(NetDemo.jComboBoxAddUserUserType.getSelectedIndex() == 1)
		{
			stUserInfo.udwLevel = NETDEV_USER_LEVEL_E.NETDEV_USER_LEVEL_USER;
		}
		boolean bRet = NetDemo.netdevsdk.NETDEV_CreateUser(NetDemo.lpUserID, stUserInfo);
        if(bRet != true)
        {
        	System.out.printf("NETDEV_CreateUser failed:%d\n", NetDemo.netdevsdk.NETDEV_GetLastError());
        	JOptionPane.showMessageDialog(null, "Create user failed. error code"+NetDemo.netdevsdk.NETDEV_GetLastError());
            return;
        }
        else 
        {
        	JOptionPane.showMessageDialog(null, "Add user success");
        	NetDemo.jTextFieldAddUserUserName.setText(null);
        	NetDemo.jTextFieldlAddUserPasswd.setText(null);
        }
        NetDemo.jButtonUserListGetUserList.doClick();
	}
}
